'''
Created on Feb 1, 2010

@author: oabalbin

This module:
a) imports a list of genes to be used as the seed core for bfrm 
b) output a file in the format required for using into bfrm. 
The out put is basically a text file space delimited: 1 2 3 4 5 \n

It needs:
2. Ordered Gene List for all the genes that are going to be used 
in the analysis. 
2. A gene list with the seed genes:
2. Find the seed genes into the genelist in 1.
3. Get the Index for that gene. 
4. Print the varin.txt file
'''

import numpy as np
import scipy as sp
from scipy import stats


def get_seed_genes(mgenelist,seedgenes):
    """
    mgenelist: master gene list a tuple of ind-gen pair value
    seedgenes: external gene list that has genes used as seed 
    return gene indicator in this particular experiment.
    return also a list of genes not found in experiment
    """
    
    gind=[]
    notfound=[]
    for i,t in enumerate(mgenelist):
        if t[0] in seedgenes:
            gind.append(i)
            print t,i
        else:
            notfound.append(t)
    return gind, notfound


def get_gen_index(expMat,extgenlist):
    """
    mgendict: master gene dictionary of gen-pair pair value
    input: external gene list that has genes used as seed 
    return gene indicator in this particular experiment.
    return also a list of genes not found in experiment
    """
    
    expMat.create_gen_index()
#    mgendict = expMat.genInd
    gind={}
    notfound=[]
    core = ['XRCC5','PRKDC','XRCC6','DDX5','PARP1','AR','NUMA1','PRPF8','RPA1','RPA2','TOP2B']
    for eg in extgenlist:
        try:
            #print mgendict[eg]
            ind = expMat.genInd[eg]
            gind[eg] = ind
            #gind.append(mgendict[eg])

        except KeyError:
            #print 'Universe gene not found in ' + eg
            notfound.append(eg)
            if eg in core:
                print 'This is a core gene not found ' + eg 

 
    return gind, notfound


def write_varin_file(seedgenes, outfile):
    """
    writes the bfrm varin.txt file using the seedgenes
    """
    i=0;
    for sg in seedgenes:
        # sg+1 because the minimun integer for bfrm is 1
        if i < 4:
            outfile.write(str(sg+1)+' ')
            i+=1
        elif i == 4:
            outfile.write(str(sg+1)+'\n')
            i=0;


    
    
    









#write_variable_genes(self, expMat, vargenes)


